package tech.shupi.babytapmobile.database

import android.content.Context
import android.util.Log
import tech.shupi.babytapmobile.types.Card
import tech.shupi.babytapmobile.types.CreateCardRequest
import tech.shupi.babytapmobile.types.UpdateCardRequest

/**
 * Repository for Card data operations
 */
class CardRepository(context: Context) {
    
    companion object {
        private const val TAG = "CardRepository"
    }
    
    private val cardDao = CardRoomDatabase.getDatabase(context).cardDao()
    
    /**
     * Get all cards
     */
    fun getAllCards(): List<Card> {
        return try {
            val entities = cardDao.getAllCards()
            entities.map { it.toCard() }
        } catch (e: Exception) {
            Log.e(TAG, "获取所有卡片失败", e)
            emptyList()
        }
    }
    
    /**
     * Get card by ID
     */
    fun getCardById(id: Int): Card? {
        return try {
            cardDao.getCardById(id)?.toCard()
        } catch (e: Exception) {
            Log.e(TAG, "获取卡片失败，ID: $id", e)
            null
        }
    }
    
    /**
     * Create a new card
     */
    fun createCard(cardRequest: CreateCardRequest): Card? {
        return try {
            val now = java.util.Date().toString()
            val entity = CardEntity(
                title = cardRequest.title,
                front_image = cardRequest.front_image,
                back_text = cardRequest.back_text,
                created_at = now,
                updated_at = now
            )
            
            val id = cardDao.insertCard(entity)
            Log.d(TAG, "创建卡片成功，ID: $id")
            
            entity.copy(id = id.toInt()).toCard()
        } catch (e: Exception) {
            Log.e(TAG, "创建卡片失败", e)
            null
        }
    }
    
    /**
     * Update an existing card
     */
    fun updateCard(id: Int, cardRequest: UpdateCardRequest): Card? {
        return try {
            val existingCard = cardDao.getCardById(id)
            if (existingCard == null) {
                Log.w(TAG, "卡片不存在，ID: $id")
                return null
            }
            
            val now = java.util.Date().toString()
            val updatedEntity = existingCard.copy(
                title = cardRequest.title,
                front_image = cardRequest.front_image,
                back_text = cardRequest.back_text,
                updated_at = now
            )
            
            val rowsAffected = cardDao.updateCard(updatedEntity)
            if (rowsAffected > 0) {
                Log.d(TAG, "更新卡片成功，ID: $id")
                updatedEntity.toCard()
            } else {
                Log.w(TAG, "更新卡片失败，ID: $id")
                null
            }
        } catch (e: Exception) {
            Log.e(TAG, "更新卡片失败，ID: $id", e)
            null
        }
    }
    
    /**
     * Delete a card
     */
    fun deleteCard(id: Int): Boolean {
        return try {
            val rowsAffected = cardDao.deleteCardById(id)
            val success = rowsAffected > 0
            if (success) {
                Log.d(TAG, "删除卡片成功，ID: $id")
            } else {
                Log.w(TAG, "删除卡片失败，ID: $id")
            }
            success
        } catch (e: Exception) {
            Log.e(TAG, "删除卡片失败，ID: $id", e)
            false
        }
    }
    
    /**
     * Get card count
     */
    fun getCardCount(): Int {
        return try {
            cardDao.getCardCount()
        } catch (e: Exception) {
            Log.e(TAG, "获取卡片数量失败", e)
            0
        }
    }
    
    /**
     * Insert multiple cards (for testing)
     */
    fun insertCards(cards: List<Card>) {
        try {
            val entities = cards.map { CardEntity.fromCard(it) }
            cardDao.insertCards(entities)
            Log.d(TAG, "批量插入 ${cards.size} 张卡片成功")
        } catch (e: Exception) {
            Log.e(TAG, "批量插入卡片失败", e)
        }
    }
} 